import { ComponentInfoType, ComponentStateType } from "./index";

/**
 * @param fe_id 当前id
 * @param componentList 组件列表
 * @returns 下一个选中selectId
 */

export const getNextSelectId = (
  fe_id: string,
  componentList: ComponentInfoType[]
) => {
  const visibleComponentList = componentList.filter((c) => !c.isHidden);
  const index = visibleComponentList.findIndex((c) => c.fe_id === fe_id);
  //没有选中元素
  if (index < 0) return "";
  let newSelectId = "";
  //只有一个元素,删除后为空
  if (visibleComponentList.length <= 1) {
    newSelectId = "";
  } else {
    //删除元素为最后一个元素
    if (index + 1 === visibleComponentList.length) {
      newSelectId = visibleComponentList[index - 1].fe_id;
    } else {
      newSelectId = visibleComponentList[index + 1].fe_id;
    }
  }
  return newSelectId;
};

/**
 * @param state state
 * @param newComponent 新组件
 * @returns
 */

export const insertNewComponent = (
  state: ComponentStateType,
  newComponent: ComponentInfoType
) => {
  const { selectId, componentList } = state;

  //未选择添加到末尾，选中则添加到被选中项下一位
  const index = componentList.findIndex((c) => c.fe_id === selectId);
  if (index < 0) {
    // 如果没找到（未选择的情况），直接添加到末尾
    return {
      ...state,
      componentList: componentList.concat(newComponent),
      selectId: newComponent.fe_id,
    };
  } else {
    return {
      ...state,
      componentList: [
        ...componentList.slice(0, index + 1),
        newComponent,
        ...componentList.slice(index + 1),
      ],
      selectId: newComponent.fe_id,
    };
  }
};
